<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="名称"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>手机号：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.mobile"
                        clearable
                        placeholder="手机号"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>等级：</label>
                <div class="table-query-input">
                    <el-cascader
                        v-model="queryData.levelId"
                        v-loading="levelList == null"
                        :show-all-levels="false"
                        clearable
                        filterable
                        :props="{
                            value: 'id',
                            label: 'name',
                            emitPath: false,
                            disabled: 'edit',
                        }"
                        :options="levelList"
                    ></el-cascader>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-plus"
                @click="go('./agentUserAdd')"
            >新增代理商用户
            </el-button>
            <el-button
                type="warning"
                style="margin-bottom: 2em"
                icon="el-icon-lock"
                :disabled="selectDisable"
                @click="batchLock(false)"
            >批量禁用
            </el-button>
            <el-button
                type="info"
                style="margin-bottom: 2em"
                icon="el-icon-unlock"
                :disabled="selectDisable"
                @click="batchLock(true)"
            >批量启用
            </el-button>
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-unlock"
                @click="asyncAgentUser(true)"
            >同步到分销
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                :tree-props="{children: 'children'}"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column prop="name" label="昵称"></el-table-column>


                <el-table-column prop="mobile" label="手机号"></el-table-column>
                <el-table-column
                    prop="levelName"
                    label="代理商等级"
                ></el-table-column>

                <el-table-column prop="banance" label="余额">
                    <template slot-scope="scope">
                        {{ priceChange(scope.row.banance) }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="accumulativeRecharge"
                    label="累计充值"
                >
                    <template slot-scope="scope">
                        {{ priceChange(scope.row.accumulativeRecharge) }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="cumulativeConsumption"
                    label="累计消费"
                >
                    <template slot-scope="scope">
                        {{ priceChange(scope.row.cumulativeConsumption) }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createdByName"
                    label="创建人"
                    width="120"
                >
                </el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建时间"
                    width="180"
                >
                </el-table-column>

                <el-table-column prop="status" label="状态" width="100">
                    <template slot-scope="scope">
                        <k-tag :tag="userStatus[scope.row.userStatus]"></k-tag>
                    </template>
                </el-table-column>

                <el-table-column
                    label="操作"
                    width="300"
                    align="center"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            v-if="!scope.row.parentId"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="go('agentUserAdd?pid=' + scope.row.id)"
                        >添加客服
                        </el-button>
                        <el-button
                            :loading="scope.row.opLoading"
                            class="warning"
                            type="text"
                            size="mini"
                            icon="el-icon-refresh-right"
                            @click="resetPass(scope.row)"
                        >重置密码
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="go('agentUserAdd?id=' + scope.row.id)"
                        >编辑
                        </el-button>
                        <!--                        <el-button-->
                        <!--                            v-if="scope.row.userStatus === 'normal'"-->
                        <!--                            :loading="scope.row.opLoading"-->
                        <!--                            class="danger"-->
                        <!--                            type="text"-->
                        <!--                            icon="el-icon-delete"-->
                        <!--                            size="mini"-->
                        <!--                            @click=" tableDelete(-->
                        <!--                                    '/user/cu/agent/user/delete',-->
                        <!--                                    {-->
                        <!--                                        id: scope.row.id-->
                        <!--                                    },-->
                        <!--                                    true-->
                        <!--                                )"-->
                        <!--                        >删除-->
                        <!--                        </el-button>-->
                        <el-button
                            v-if="scope.row.userStatus === 'normal'"
                            :loading="scope.row.opLoading"
                            type="text"
                            size="mini"
                            class="warning"
                            icon="el-icon-lock"
                            @click="changeUserStatus(scope.row, false)"
                        >禁用
                        </el-button>
                        <el-button
                            v-if="scope.row.userStatus === 'lock'"
                            :loading="scope.row.opLoading"
                            size="mini"
                            type="text"
                            icon="el-icon-unlock"
                            @click="changeUserStatus(scope.row, true)"
                        >启用
                        </el-button>
                        <el-button
                            v-if="!scope.row.parentId"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-plus"
                            @click="recharge(scope.row)"
                        >充值
                        </el-button>
                        <!--                        <el-button-->
                        <!--                            v-if="!scope.row.parentId"-->
                        <!--                            class="primary"-->
                        <!--                            type="text"-->
                        <!--                            size="mini"-->
                        <!--                            icon="el-icon-connection"-->
                        <!--                            @click="bindGroupTake(scope.row)"-->
                        <!--                        >绑定平台-->
                        <!--                        </el-button>-->
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            :before-close="dialogClose"
            custom-class="one-dialog"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="8em"
                :rules="dataFormRule"
                class="table-edit-from"
            >
                <el-form-item label="余额" prop="balance">
                    <el-input v-model="dataForm.banance" disabled></el-input>
                </el-form-item>
                <el-form-item label="充值类型" prop="type">
                    <el-select v-model="dataForm.type" placeholder="请选择">
                        <el-option
                            v-for="item in agentRechargeType"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="充值金额" prop="amount">
                    <el-input-number
                        v-model="dataForm.priceYuan"
                        :precision="2"
                        :step="1"
                    ></el-input-number>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input
                        v-model="dataForm.remark"
                        type="textarea"
                        :rows="4"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="chargeFormSave()"
                >保 存</el-button
                >
            </span>
        </el-dialog>
        <el-dialog title="绑定平台" :visible.sync="bindGroupVisible" width="20%">
            <el-form :model="dataForm" label-width="6em">
                <el-form-item label="绑定平台">
                    <el-select v-model="dataForm.bindGroupIds" filterable clearable multiple placeholder="请选择平台">
                        <el-option
                            v-for="item in groupList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                    不设置即为通用
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="bindGroupVisible=false"
                >取 消</el-button
                >
                <el-button
                    type="primary"
                    @click="bindGroup()"
                >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {execCall, TablePage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {treeList2Tree, beanCopy} from "@/utils/index.js";
import {get, put, post} from "@/api/request";
import {fetchAgentUserSimpleDetail, fetchAgentLevelList, getAgentList, syncAgentUser} from "@/api/user";


export default {
    name: "AgentUserList",
    components: {},
    mixins: [TablePage],
    data() {
        return {
            dataFormRule: {
                type: [
                    {
                        required: true,
                        message: "请选择充值类型",
                        trigger: "change"
                    }
                ],
            },
            agentLoading: false,
            agentList: [],
            queryData: {
                name: "",
                mobile: "",
                role: false,
                position: true,
                positionId: null,
                showLevel: true,
                orders: [{
                    asc: false,
                    column: "sub.created_time"
                }]
            },
            agentRechargeType: [
                {
                    value: "normal",
                    label: "普通充值"
                },
                {
                    value: "refund",
                    label: "充值退款"
                }
            ],
            positionList: null,
            levelList: null,
            dataForm: {
                agentId: null,
                id: null,
                remark: null,
                type: "normal",
                amount: null,
                banance: 100
            },
            initDataForm: {
                agentId: null,
                id: null,
                remark: null,
                type: "normal",
                amount: null,
                banance: 100
            },
            bindGroupVisible: false
        };
    },
    computed: {
        ...mapState({
            userStatus: state => state.status.userStatus
        })
    },
    watch: {
        $route: function (to, from) {
            // 拿到目标参数 to.query.id 去再次请求数据接口
            this.refresh = this.$route.query.refresh;
            if (from.name === "AgentUserAdd" && this.refresh) {
                this.search();
            }
        }
    },
    created() {
        // this.loadPosition();
        this.loadLevel();
    },
    mounted() {
    },

    methods: {
        asyncAgentUser() {
            syncAgentUser()


        },
        search(queryData) {
            this.loadTable("/user/cu/agent/user/page", queryData);
        },
        chargeFormSave() {
            return new Promise((r, j) => {
                this.$refs.dataForm.validate(valid => {
                    if (valid) {
                        r();
                    } else {
                        j();
                    }
                });
            }).then(() => {
                this.submitFlag = true;
                post("/user/cu/agent/recharge/update", this.dataForm)
                    .then(res => {
                        this.dialogFormVisible = false;
                        this.search();
                    })
                    .finally(() => {
                        this.submitFlag = false;
                    })
                    .catch(e => {
                        console.error(e);
                    });
            });
        },
        recharge(row) {
            this.dialogFormVisible = true;
            this.dialogFormTitle = "充值";
            this.dataForm = {
                userId: null,
                id: null,
                remark: null,
                type: "normal",
                priceYuan: 100,
                banance: null
            };
            fetchAgentUserSimpleDetail({id: row.id})
                .then(res => {
                    this.dataForm.userId = res.id;
                    this.dataForm.banance = this.priceChange(res.banance);
                })
                .finally(() => {
                });
        },
        priceChange(number) {
            if (!number) {
                return "0.00元";
            }
            const bs = number / 100;
            return bs.toFixed(2) + "元";
        },
        loadLevel() {
            fetchAgentLevelList({
                size: 1000
            }).then(data => {
                this.levelList = data;
            });
        },
        getAgentList() {
            this.agentLoading = true;
            getAgentList({size: 1000})
                .then(res => {
                    this.agentList = res;
                })
                .finally(() => {
                    this.agentLoading = false;
                });
        },
        async batchLock(status) {
            if (!status) {
                await this.$confirm("确定禁用这些账号吗？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                });
            }
            this.tableData.forEach(v => {
                if (this.tableSelect.includes(v.id)) {
                    this.changeUserStatus(v, status);
                }
                v.children.forEach(c => {
                    if (this.tableSelect.includes(c.id)) {
                        this.changeUserStatus(c, status);
                    }
                })
            })
        },
        changeUserStatus(data, status) {
            // 禁用启用对分销系统有连带影响，前期为了快速开发，直接新增一个请求接口，不在原接口上修改
            this.$confirm({
                title: "确定要同步禁用分销代理商用户吗？",
                content: "取消则不禁用分销代理商用户，请谨慎操作！",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                data.opLoading = true;
                post(`/user/cu/agent/user/enable/${status}/${data.id}`)
                    .then(res => {
                        data.userStatus = status ? "normal" : "lock";
                        data.opLoading = false;
                    })
                    .finally(() => {
                        data.opLoading = false;
                        this.search()
                    });
                post(`/user/distributionUser/disabled`,{
                    agentId: data.id,
                })
            }).catch(() => {
                data.opLoading = true;
                post(`/user/cu/agent/user/enable/${status}/${data.id}`)
                    .then(res => {
                        data.userStatus = status ? "normal" : "lock";
                        data.opLoading = false;
                    })
                    .finally(() => {
                        data.opLoading = false;
                        this.search()
                    });
            })

        },
        loadPosition() {
            get("/user/cu/admin/position/list").then(res => {
                this.positionList = treeList2Tree(res);
            });
        },
        async resetPass(row) {
            await this.$confirm("确定将密码重置为tk123456吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            });
            post(`/user/cu/user/change/password-admin/${row.id}`, {
                newPassword: "tk123456"
            })
                .then(() => {
                    this.$message.success("重置成功");
                })
                .catch(e => {
                    this.$message.error("重置失败");
                });
        },
        bindGroupTake(data) {
            this.bindGroupVisible = true;
            this.dataForm = data;
            console.log("data", data)
            this.loadGroupList();
        },
        bindGroup() {
            this.dataForm.bindGroupIds = JSON.stringify(this.dataForm.bindGroupIds);
            put("/user/cu/agent/user/bind-group", this.dataForm)
                .then(res => {
                    this.$message.success("绑定成功");
                    this.bindGroupVisible = false;
                })
        },

    }
};
</script>

<style lang="scss" scoped></style>
